package com.xiongyingqi.sms;
 

import java.util.*;
import java.io.*;

import org.apache.log4j.Logger;
import org.smslib.*;
import org.smslib.AGateway.GatewayStatuses;
import org.smslib.Message.MessageEncodings;
import org.smslib.modem.*;

import com.xiongyingqi.queue.QueueManager;
import com.xiongyingqi.queue.QueueMessageManager;
import com.xiongyingqi.sms.event.MessageListener;

public class SMSService {
	public static final Logger logger = Logger.getLogger(SMSService.class);
	private static Service service;
	private static CheckStatusLoadBalance loadBalancer = new CheckStatusLoadBalance();
	private static QueueMessageManager queueMessageManager = QueueMessageManager.getInstance();

	public static Set<SerialModemGateway> loadDeviceResources() {
		Set<SerialModemGateway> gateways = new LinkedHashSet<SerialModemGateway>();
		InputStream inputStream = SMSService.class.getClassLoader()
				.getResourceAsStream("device.properties");
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
			String gateWays = properties.getProperty("GateWays");
			StringTokenizer stringTokenizer = new StringTokenizer(gateWays, ",");
			while (stringTokenizer.hasMoreElements()) {
				String gateWayId = (String) stringTokenizer.nextElement();
				gateWayId = gateWayId.trim();
				String comPort = properties.getProperty(gateWayId + ".comPort");
				int baudRate = Integer.parseInt(properties
						.getProperty(gateWayId + ".baudRate"));
				String manufacturer = properties.getProperty(gateWayId
						+ ".manufacturer");
				String model = properties.getProperty(gateWayId + ".model");
				System.out.println(gateWayId);
				System.out.println(comPort);
				System.out.println(baudRate);
				System.out.println(model);
				SerialModemGateway gateway = new SerialModemGateway(gateWayId,
						comPort, baudRate, manufacturer, model);
				gateways.add(gateway);
			}
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
		return gateways;
	}

	/**
	 * 当网关出现故障时，重新检查网关 <br>
	 * 2013-9-13 下午3:31:31
	 */
	public static void validateService() {
		Collection<AGateway> gateways = service.getGateways();
		for (AGateway gateway : gateways) {
			GatewayStatuses statuses = gateway.getStatus();
			if(statuses == GatewayStatuses.STOPPED || statuses == GatewayStatuses.FAILURE){
				try {
					gateway.stopGateway();
					gateway.startGateway();
				} catch (TimeoutException e) {
					e.printStackTrace();
					logger.error(e);
				} catch (GatewayException e) {
					e.printStackTrace();
					logger.error(e);
				} catch (IOException e) {
					e.printStackTrace();
					logger.error(e);
				} catch (InterruptedException e) {
					e.printStackTrace();
					logger.error(e);
				}
			}
		}
	}

	/**
	 * 启动服务 <br>
	 * 2013-7-29 下午2:41:22
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Service startService() {
		OutboundNotification outboundNotification = new OutboundNotification();
		InboundNotification inboundNotification = new InboundNotification();
		CallNotification callNotification = new CallNotification();
		// System.out.println("DeviceSearcher.getPortId().getName() ========= "
		// + DeviceSearcher.getPortId().getName());// 900E 1800
		// System.out.println("DeviceSearcher.getBaudPort() ========= " +
		// DeviceSearcher.getBaudPort());
		Service service = Service.getInstance();
		service.setLoadBalancer(loadBalancer);
		service.setOutboundMessageNotification(outboundNotification);
		service.setInboundMessageNotification(inboundNotification);
		service.setCallNotification(callNotification);
		service.S.SERIAL_POLLING = true;

		Set<SerialModemGateway> gateways = loadDeviceResources();
		
		int priority = 0;
		for (Iterator iterator = gateways.iterator(); iterator.hasNext();) {
			SerialModemGateway gateway = (SerialModemGateway) iterator.next();
			// SerialModemGateway gateway = new SerialModemGateway("kingray",
			// "COM4",
			// 9600, "WAVECOM MODEM", "MULTIBAND  900E  1800",
			// service.getLogger()); // AT+CGMM
			gateway.setInbound(true);
			gateway.setOutbound(true);
			gateway.setSimPin("0000");

			// System.out.println("GSM Modem信息:");
			// try {
			// System.out.println("  厂家: " + gateway.getManufacturer());
			// System.out.println("  型号: " + gateway.getModel());
			// System.out.println("  序列号: " + gateway.getSerialNo());
			// System.out.println("  SIM IMSI: " + gateway.getImsi());
			// System.out.println("  信号强度: " + gateway.getSignalLevel() + "%");
			// System.out.println("  电池容量: " + gateway.getBatteryLevel() + "%");
			// System.out.println();
			// } catch (TimeoutException e) {
			// e.printStackTrace();
			// } catch (GatewayException e) {
			// e.printStackTrace();
			// } catch (IOException e) {
			// e.printStackTrace();
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
			
			try {
				service.addGateway(gateway);
				loadBalancer.setGatewayPriority(gateway, priority++);// 设置优先级
			} catch (GatewayException e) {
				logger.error(e);
				e.printStackTrace();
			}
		}
		try {
			service.startService();
			for (Iterator iterator = gateways.iterator(); iterator.hasNext();) {
				SerialModemGateway gateway = (SerialModemGateway) iterator
						.next();
				System.out.println();
				System.out.println("Modem Information:");
				try {
					System.out.println("  Manufacturer: " + gateway.getManufacturer());
					System.out.println("  Model: " + gateway.getModel());
					System.out.println("  Serial No: " + gateway.getSerialNo());
					System.out.println("  SIM IMSI: " + gateway.getImsi());
					System.out.println("  Signal Level: " + gateway.getSignalLevel() + " dBm");
					System.out.println("  Battery Level: " + gateway.getBatteryLevel() + "%");
					System.out.println();
				} catch (TimeoutException e1) {
					e1.printStackTrace();
				} catch (GatewayException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				
			}
			
		} catch (TimeoutException e) {
			e.printStackTrace();
			logger.error(e);
		} catch (GatewayException e) {
			e.printStackTrace();
			logger.error(e);
			Collection<AGateway> gateways2 = service.getGateways();
			for (Iterator<AGateway> iterator = gateways2.iterator(); iterator.hasNext();) {
				AGateway gateway = (AGateway) iterator.next();
				
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e);
		} catch (InterruptedException e) {
			e.printStackTrace();
			logger.error(e);
		} catch (SMSLibException e) {
			e.printStackTrace();
			logger.error(e);
		}

		// 发送WAP短信.
		// OutboundWapSIMessage wapMsg = new
		// OutboundWapSIMessage("+8613601019694", new
		// URL("https://www.sendsms.cn/"), "欢迎访问金笛短信网!");
		// srv.sendMessage(wapMsg);
		// System.out.println(wapMsg);

		// 发送短信（异步发送，待发送短信进入队列，发送时不做任何等待）
		// msg = new OutboundMessage("+869999999999", "Wrong number!");
		// msg.setPriority(OutboundMessage.Priorities.LOW);
		// srv.queueMessage(msg, gateway.getGatewayId());
		// msg = new OutboundMessage("+868888888888", "Wrong number!");
		// msg.setPriority(OutboundMessage.Priorities.HIGH);
		// srv.queueMessage(msg, gateway.getGatewayId());

		// System.out.println("进入等待状态... - 按回车键退出.");
		// System.in.read();
		SMSService.service = service;
		return service;
	}

	public static void sendSms(String phoneNumber, String content)
			throws TimeoutException, GatewayException, IOException,
			InterruptedException {
		if (service == null) {
			startService();
		}
		// 发送短信（同步发送，发送完成才执行下一步）.
		OutboundMessage msg = new OutboundMessage(phoneNumber, content);
		msg.setEncoding(MessageEncodings.ENCUCS2);

		queueMessageManager.queueMessage(msg);// 使用队列的形式
//		service.queueMessage(msg);// 使用队列的形式
//		 service.sendMessage(msg);
	}

	public static void sendSmses(List<OutboundMessage> messages) {
		if (service == null) {
			startService();
		}
		for (Iterator iterator = messages.iterator(); iterator.hasNext();) { // 设置字符集
			OutboundMessage outboundMessage = (OutboundMessage) iterator.next();
			outboundMessage.setEncoding(MessageEncodings.ENCUCS2);
		}
//		try {
//			service.queueMessages(messages);
//		} catch (Exception e) {
//			logger.error(e);
//			validateService();
//		}
		
		queueMessageManager.queueMessages(messages);// 使用队列的形式
//		 try {
//			service.sendMessages(messages);
//		} catch (Exception e) {
//			validateService();
//		}
	}

	public static void sendSmses(String content, List<String> phoneNumbers) {
		List<OutboundMessage> messages = new LinkedList<OutboundMessage>();
		for (Iterator iterator = phoneNumbers.iterator(); iterator.hasNext();) {
			String phoneNumber = (String) iterator.next();
			OutboundMessage message = new OutboundMessage(phoneNumber, content);
			messages.add(message);
		}
		sendSmses(messages);
	}

	// public static void addSmsToQueue(String phoneNumber, String content)
	// throws TimeoutException, GatewayException, IOException,
	// InterruptedException{
	// if(service == null){
	// startService();
	// }
	// // 发送短信（同步发送，发送完成才执行下一步）.
	// OutboundMessage msg = new OutboundMessage(phoneNumber, content);
	// msg.setEncoding(MessageEncodings.ENCUCS2);
	//
	// service.queueMessage(msg);
	// // service.sendMessage(msg);
	// System.out.println(msg);
	// }

	public static void stopService() {
		try {
			service.stopService();
		} catch (TimeoutException e) {
			e.printStackTrace();
			logger.error(e);
		} catch (GatewayException e) {
			e.printStackTrace();
			logger.error(e);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e);
		} catch (InterruptedException e) {
			e.printStackTrace();
			logger.error(e);
		} catch (SMSLibException e) {
			e.printStackTrace();
			logger.error(e);
		}
	}

	public static void main(String args[]) {
		loadDeviceResources();
		
		// loadDeviceResources(null);
		logger.error("asfsf");
		// SMSService app = new SMSService();
		// try {
		// app.startService();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// try {
		// app.sendSms("15084818017", "linux 短信猫测试");
		// app.sendSms("15084818017", "linux 短信猫测试2");
		// } catch (TimeoutException e) {
		// e.printStackTrace();
		// } catch (GatewayException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// // app.sendSms("18520802082", "linux 短信猫测试");
		// try {
		// app.service.stopService();
		// } catch (TimeoutException e) {
		// e.printStackTrace();
		// } catch (GatewayException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// Scanner scanner = new Scanner(System.in); // , "utf-8"
		// String nextLine = null;
		// while (true) {
		// String phoneNumber = null;
		// String content = null;
		// // System.out.println("请输入电话号码！"); // 13480657523
		// // if((nextLine = scanner.nextLine()) != null &&
		// !"".equals(nextLine.trim())){
		// // phoneNumber = nextLine;
		// // } else {
		// // break;
		// // }
		// System.out.println("请输入内容！");
		// if((nextLine = scanner.nextLine()) != null &&
		// !"".equals(nextLine.trim())){
		// content = nextLine;
		// System.out.println("content ============ " + content);
		// } else {
		// break;
		// }
		// // app.sendSms(phoneNumber, content);
		// }

	}

	/**
	 * Service
	 * 
	 * @return the service
	 */
	public static Service getService() {
		return service;
	}

}
